package com.itheima.task.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 */
@Configuration
@Slf4j
public class ThreadPoolConfig {

    @Value("${audit.thread-pool.core-size:10}")
    private int coreSize;

    @Value("${audit.thread-pool.max-size:20}")
    private int maxSize;

    @Value("${audit.thread-pool.queue-capacity:1000}")
    private int queueCapacity;

    /**
     * 审核任务线程池
     */
    @Bean(name = "auditTaskExecutor")
    public ThreadPoolTaskExecutor auditTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        // 核心线程数
        executor.setCorePoolSize(coreSize);
        
        // 最大线程数
        executor.setMaxPoolSize(maxSize);
        
        // 队列容量
        executor.setQueueCapacity(queueCapacity);
        
        // 线程名称前缀
        executor.setThreadNamePrefix("audit-task-");
        
        // 拒绝策略：调用线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        
        // 允许核心线程超时
        executor.setAllowCoreThreadTimeOut(true);
        
        // 线程空闲时间（秒）
        executor.setKeepAliveSeconds(60);
        
        // 等待所有任务完成后关闭
        executor.setWaitForTasksToCompleteOnShutdown(true);
        
        // 最大等待时间（秒）
        executor.setAwaitTerminationSeconds(60);
        
        // 初始化
        executor.initialize();
        
        log.info("审核任务线程池初始化完成: coreSize={}, maxSize={}, queueCapacity={}", 
                coreSize, maxSize, queueCapacity);
        
        return executor;
    }
}

